<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <my-bread :level1="'用户管理'" :level2="'活动列表'"/>
      <el-row class="search-row">
        <el-col>
          <el-input
            placeholder="请输入内容"
            v-model="query"
            clearable
            @clear="loadUserList"
            class="query"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
          <el-button type="success" @click="showAddUser">添加用户</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table :data="userList" border height="660" style="width: 100%">
      <el-table-column type="index" width="50" align="center"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time | fmtdate}}</template>
      </el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="changeMgState(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle @click="showEditUserDia(scope.row)"></el-button>
          <el-button
            type="success"
            icon="el-icon-check"
            circle
            @click="showSetUserRoleDia(scope.row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="showDelUserMsgBox(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top:6px"
    ></el-pagination>

    <el-dialog title="添加用户" :visible.sync="dialogFormVisibleAdd" width="500px">
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑用户" :visible.sync="dialogFormVisibleEdit" width="500px">
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleRole" width="500px">
      <el-form :model="form">
        <el-form-item label="用户名">{{currUsername}}</el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currRoleId">
            <el-option label="请选择" value="-1"></el-option>
            <el-option v-for="(v,i) in roles" :key="i" :label="v.roleName" :value="v.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleRole = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
export default {
  data() {
    return {
      query: "",
      pagenum: 1,
      pagesize: 5,
      total: 0,
      userList: [],
      dialogFormVisibleAdd: false,
      dialogFormVisibleEdit: false,
      dialogFormVisibleRole: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      currRoleId: -1,
      roleId: "",
      currUsername: "",
      roles: [],
      formLabelWidth: "100px"
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const res = await this.$axios.get(
        `users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${this.pagesize}`
      );
      const {
        meta: { status, msg },
        data: { users, total }
      } = res.data;
      if (status === 200) {
        this.$message({
          message: msg,
          type: "success",
          duration: 1000
        });
        this.userList = users;
        this.total = total;
      } else {
        this.$message.error(msg);
      }
    },
    searchUser() {
      this.getUserList();
    },
    loadUserList() {
      this.getUserList();
    },
    showAddUser() {
      this.dialogFormVisibleAdd = true;
    },
    async addUser() {
      this.dialogFormVisibleAdd = false;
      const res = await this.$axios.post("users", this.form);
      const {
        meta: { msg, status }
      } = res.data;
      if (status === 201) {
        this.$message({
          message: msg,
          type: "success",
          duration: 1000
        });
        this.getUserList();
        this.form = {};
      } else {
        this.$message({
          message: msg,
          type: "error",
          duration: 1000
        });
        this.form = {};
      }
    },
    showDelUserMsgBox(id) {
      this.$confirm("是否永久删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await this.$axios.delete(`users/${id}`);
          if (res.data.meta.status === 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.pagenum = 1;
            this.getUserList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    showEditUserDia(user) {
      this.dialogFormVisibleEdit = true;
      this.form = user;
    },
    async editUser() {
      this.dialogFormVisibleEdit = false;
      const res = await this.$axios.put(`users/${this.form.id}`, this.form);
      if (res.data.meta.status === 200) {
        this.$message({
          type: "success",
          message: res.data.meta.msg
        });
      }
    },
    async changeMgState(user) {
      const res = await this.$axios.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      if (res.data.meta.status === 200) {
        this.$message({
          type: "success",
          message: res.data.meta.msg
        });
      }
    },
    async showSetUserRoleDia(user) {
      this.dialogFormVisibleRole = true;
      this.currUsername = user.username;
      this.roleId = user.id;
      const res = await this.$axios.get(`users/${user.id}`);
      const resR = await this.$axios.get(`roles`);
      this.roles = resR.data.data;
      this.currRoleId = res.data.data.rid;
    },
    async setUserRole() {
      this.dialogFormVisibleRole = false;
      const res = await this.$axios.put(`users/${this.roleId}/role`, {
        rid: this.currRoleId
      });
      if (res.data.meta.status === 200) {
        this.$message({
          type: "success",
          message: res.data.meta.msg
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.meta.msg
        });
      }
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.pagenum = 1;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.pagenum = val;
      this.getUserList();
    }
  }
};
</script>
<style lang="scss">
.search-row {
  margin-top: 20px;
}
.query {
  width: 300px;
  margin-right: 10px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  height: 100%;
}
</style>


